//
//  TJOauthViewController.swift
//  TJSinaWeibo
//
//  Created by 唐后能 on 16/4/9.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit
import SVProgressHUD
class TJOauthViewController: UIViewController {

    // MARK: - 重写系统方法.
    // 自定义控制器的view.
    override func loadView() {
        view = webView
        // 设置webView代理.
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        view.backgroundColor = UIColor.redColor()
        // 1,设置导航栏两侧按钮.
        setupNavItem ()
        
        // 2,加载webView.
        loadWebVeiw ()
        
        // 3,添加HUD指示器.
        SVProgressHUD.showWithStatus("正在加载...")
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Black)
    }
    
    // MARK: - 私有方法.
    // 加载webView.
    private func loadWebVeiw (){
        let urlString = oauthURLString + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }
    
//    // MARK: 获取access tocken方法.
//    private func loadAccessTocken (code:String) {
//    
//        // 获取token的URL.(新浪提供的)
//        let urlString = "https://api.weibo.com/oauth2/access_token"
//        
//        // 请求参数.
//        let prameters:[String:String] = [
//        
//            "client_id": client_id,
//            "client_secret": client_secret,
//            "grant_type": "authorization_code",
//            "code": code,
//            "redirect_uri": redirect_uri
//        ]
//        
//        // 发送请求.
//        // 下面方法已经过时.
////        TJNetWorkManager.shareNetWorkManager.POST(urlString, parameters: prameters, success: { (_, result) -> Void in
////            print("result=\(result!)")
////            }) { (_, error) -> Void in
////                print("error=\(error)")
////        }
//        // 有progress的没有过时.
//        TJNetWorkManager.shareNetWorkManager.POST(urlString, parameters: prameters, progress: nil, success: { (_, responseObject) -> Void in
////            TJPrint("请求成功:result= \(responseObject)")
//            // 将返回结果转为字典.
//            let result = responseObject as? [String:AnyObject]
//            if let dict = result {
//            
//                // 进行字典转模型.
//                let userAccount = TJUserAcount(dict: dict)
////                TJPrint("字典转模型成功\(userAccount)")
//                
//                // 归档模型数据.
//                NSKeyedArchiver.archiveRootObject(userAccount, toFile: accountPath)
//            }
//            
//            }) { (_, error) -> Void in
//                TJPrint(error)
//        }
//    }
    
    // 设置导航栏两侧按钮.
    private func setupNavItem (){
    
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("fillBtnClicked"))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("cancelBtnClicked"))
    }
    
    // MARK:按钮点击事件.
    // 填充.
    @objc func fillBtnClicked(){
    
        //document.getElementById('userId').value = '243321257@qq.com'
        //document.getElementById('passwd').value = 'thn&acn243321257'
        // 拼接js代码.
        let js = "document.getElementById('userId').value = '15814729452';document.getElementById('passwd').value = 'thn&acn243321257'"
        // 让webView直行js代码.
        webView.stringByEvaluatingJavaScriptFromString(js)
        
    }
    // 取消.
    @objc func cancelBtnClicked(){
        
        dismissViewControllerAnimated(true, completion: nil)
    }

    // MARK:懒加载
    lazy var webView = UIWebView()
}



    // MARK:webView代理方法.
extension TJOauthViewController:UIWebViewDelegate {

    // webView加载完成后调用.
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    // webVeiw加载失败后调用.
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
        // print(error)
        if error?.code == 102 { //点击取消或授权时候出现的错误代码.
        
            return
        }
        SVProgressHUD.showErrorWithStatus("加载出错啦!")
        
    }
    
    // 是否要根据request进行加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
//        print("/////////:\(request.URL)")
        let isOauthString = request.URL!.absoluteString.hasPrefix(redirect_uri)
        // 1,判断是否是授权回调地址.
        if !isOauthString { // 不是授权回调地址.
            return true
        }
        
        // 再判断是点击了取消,还是授权.
        let query = request.URL!.query //GET请求?后面的字符串.
        //            print(query)
        let isCodeString = query!.hasPrefix("code=")
        if isCodeString { //如果是code=,点击了授权.
            // 将code=后面的字符串截取出来.
            let index = "code=".endIndex
            let code = query?.substringFromIndex(index)
//            print(code!)
            // 调用viewModel的方法,获取token.
            TJAccountViewModel.shareUserAccount.loadAccessTocken(code!, loadAccessTokenCallBack: { (error) -> () in
                if error == nil {
                
                    // 加载成功,关闭界面.
                    self.cancelBtnClicked()
                    SVProgressHUD.dismiss()
                    // 跳转到欢迎界面.
                   (UIApplication.sharedApplication().delegate as! AppDelegate).changeWindowRootVC(TJWelcomeViewController())
                    
                }else {
                
                    // 加载失败.
                    SVProgressHUD.showErrorWithStatus("网络不给力!")
                }
            })
        }else { // 点击了取消.
            
            cancelBtnClicked()
        }
        return false
    }
}


